//
//  SecurePayInputView.swift
//  777Proj
//
//  Created by 陈宇 on 2017/5/10.
//  Copyright © 2017年 🐜. All rights reserved.
//

import UIKit

class SecurePayInputView: UIView, UIKeyInput {
    
    private var textStorage = NSTextStorage()

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    var hasText: Bool {
        return textStorage.length > 0
    }

    func insertText(_ text: String) {
        let cs = NSCharacterSet(charactersIn: "0123456789").inverted
        let resultString = text.components(separatedBy: cs).joined()
        
        if text == resultString {
            textStorage.append(NSAttributedString(string: text))
            setNeedsDisplay()
        }
    }
    
    func deleteBackward() {
        if hasText {
            textStorage.deleteCharacters(in: NSRange(location: self.textStorage.length - 1, length: 1))
            setNeedsDisplay()
        }
    }
    
    
    private var keyboardType: UIKeyboardType {
        return .numberPad
    }
    
    private var isSecureTextEntry: Bool {
        return true
    }
    
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !isFirstResponder {
            becomeFirstResponder()
        }
    }
}
